package com.example.distortionmeter.ui.components

import android.annotation.SuppressLint
import android.graphics.Paint
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.mutableLongStateOf

@SuppressLint("UnrememberedMutableState")
@Composable
fun WaveformDisplay(title: String, data: List<Float>, color: Color) {
    val animatedProgress by animateFloatAsState(
        targetValue = if (data.isNotEmpty()) 1f else 0f,
        animationSpec = tween(500)
    )
    val maxValue = 2047.5f.coerceAtLeast(1e-6f)// ADC数据最大值
    // 触摸交互状态
    var touchPosition by remember { mutableStateOf<Offset?>(null) }
    var selectedIndex by remember { mutableStateOf<Int?>(null) }

    // 控制自动隐藏
    var lastTouchTime by remember { mutableLongStateOf(0L) }
    val showIndicator by derivedStateOf {
        System.currentTimeMillis() - lastTouchTime < 10000 // 10秒无操作自动隐藏
    }
    // 自动隐藏协程
    LaunchedEffect(showIndicator) {
        if (!showIndicator) {
            touchPosition = null
            selectedIndex = null
        }
    }


    Card(
        elevation = CardDefaults.cardElevation(2.dp),
        shape = MaterialTheme.shapes.large
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSurface
                )
                // 数值显示
                if (showIndicator && selectedIndex != null) {
                    Text(
                        text = "X: ${selectedIndex ?: "N/A"}  Y: ${selectedIndex?.let {
                                "%.2f".format(data.getOrNull(it) ?: 0f)} ?: "N/A"
                        }",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f)
                    )
                }
            }
                Spacer(Modifier.height(12.dp))
                Canvas(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(180.dp)
                        .pointerInput(Unit) {
                            detectTapGestures { offset ->
                                lastTouchTime = System.currentTimeMillis()
                                touchPosition = offset
                                if (data.isNotEmpty()) {
                                    val stepX = size.width / (data.size - 1)
                                    selectedIndex = (offset.x / stepX + 0.5f)
                                        .toInt() // 四舍五入
                                        .coerceIn(data.indices) // 更安全的边界控制
                                }
                            }
                        }
                ) {
                    // 绘制背景网格（先绘制网格）
                    drawGrid(1.dp.toPx())

                    // 创建波形路径
                    if (data.isNotEmpty()) {
                        val waveformPath = Path().apply {
                            val stepX = size.width / (data.size - 1)
                            moveTo(0f, size.height / 2 * (1 - data.first() / maxValue))
                            data.forEachIndexed { i, value ->
                                val normalizedY = (data[i] / maxValue).coerceIn(-1f, 1f) // 仅用于绘制
                                lineTo(i * stepX, size.height / 2 * (1 - normalizedY))
                            }
                        }

                        drawPath(
                            path = waveformPath,
                            color = color,
                            alpha = animatedProgress,
                            style = Stroke(
                                width = 2.dp.toPx(),
                                pathEffect = PathEffect.cornerPathEffect(8f)
                            )
                        )
                    }

                    // 绘制触摸点信息
                    if (showIndicator) {
                        touchPosition?.let { pos ->
                            val displayPos = pos.copy(
                                x = pos.x.coerceIn(0f, size.width),
                                y = pos.y.coerceIn(0f, size.height)
                            )
                            // 绘制垂直线
                            drawLine(
                                color = Color.Green,
                                start = Offset(displayPos.x, 0f),
                                end = Offset(displayPos.x, size.height),
                                strokeWidth = 1.dp.toPx()
                            )
                        }
                    }
                }
            }
        }
    }
private fun DrawScope.drawGrid(lineWidth: Float) {
    val color = Color.Gray.copy(alpha = 0.3f)

    // 垂直网格
    for (i in 1..4) {
        val x = size.width * i / 5
        drawLine(color, Offset(x, 0f), Offset(x, size.height), lineWidth)
    }

    // 水平网格
    for (i in 1..2) {
        val y = size.height * i / 3
        drawLine(color, Offset(0f, y), Offset(size.width, y), lineWidth)
    }

    // 中心线
    drawLine(
        color = Color.Gray,
        start = Offset(0f, center.y),
        end = Offset(size.width, center.y),
        strokeWidth = lineWidth
    )
}


@SuppressLint("UnrememberedMutableState")
@Composable
fun HarmonicBarsDisplay(title: String, data: List<Float>, color: Color) {
    // 触摸交互状态
    var touchPosition by remember { mutableStateOf<Offset?>(null) }
    var selectedHarmonic by remember { mutableStateOf<Int?>(null) }

    // 自动隐藏控制
    var lastTouchTime by remember { mutableLongStateOf(0L) }
    val showIndicator by derivedStateOf {
        System.currentTimeMillis() - lastTouchTime < 10000 // 10秒无操作隐藏
    }

    LaunchedEffect(showIndicator) {
        if (!showIndicator) {
            touchPosition = null
            selectedHarmonic = null
        }
    }

    Card(
        elevation = CardDefaults.cardElevation(2.dp),
        shape = MaterialTheme.shapes.large
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(title, style = MaterialTheme.typography.titleMedium)
                // 数值显示
                if (showIndicator && selectedHarmonic != null) {
                    Text(
                        text = "H${selectedHarmonic}: ${data.getOrNull((selectedHarmonic ?: 1) - 1)?.let { "%.2f".format(it) } ?: "N/A"}%",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f)
                    )
                }
            }
            Spacer(Modifier.height(12.dp))
            Canvas(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(180.dp)
                    .pointerInput(Unit) {
                        detectTapGestures { offset ->
                            lastTouchTime = System.currentTimeMillis()
                            touchPosition = offset
                            selectedHarmonic = calculateSelectedHarmonic(offset.x, size.width)
                        }
                    }
            ) {
                if (data.size != 10) return@Canvas

                val barWidth = size.width / 12
                val maxValue = data.maxOrNull() ?: 1f

                data.forEachIndexed { index, value ->
                    val isSelected = (index + 1) == selectedHarmonic
                    val barHeight = (value / maxValue) * size.height * 0.8f

                    // 绘制柱状图
                    drawRect(
                        color = if (isSelected && showIndicator) Color.Yellow else color,
                        topLeft = Offset(
                            x = barWidth * (index + 1) + barWidth * 0.2f,
                            y = size.height - barHeight
                        ),
                        size = Size(width = barWidth * 0.6f, height = barHeight)
                    )

                    // 绘制谐波次数标签
                    drawContext.canvas.nativeCanvas.apply {
                        drawText(
                            "${index + 1}",
                            barWidth * (index + 1) + barWidth * 0.5f,
                            size.height - 8f,
                            android.graphics.Paint().apply {
                                textSize = 12.sp.toPx()
                                this.color = android.graphics.Color.GRAY
                                textAlign = android.graphics.Paint.Align.CENTER
                            }
                        )
                    }

                    // 绘制选中状态
                    if (isSelected && showIndicator) {
                        drawRect(
                            color = Color.White.copy(alpha = 0.3f),
                            topLeft = Offset(
                                x = barWidth * (index + 1) + barWidth * 0.2f,
                                y = size.height - barHeight
                            ),
                            size = Size(width = barWidth * 0.6f, height = barHeight),
                            style = Stroke(width = 2.dp.toPx())
                        )
                    }
                }
            }
        }
    }
}

private fun calculateSelectedHarmonic(touchX: Float, totalWidth: Int): Int? {
    val barWidth = totalWidth / 12.0f
    return (touchX / barWidth - 1).toInt().takeIf {
        it in 0..9
    }?.plus(1)
}

